package repo

import (
	"time"

	"github.com/pingcap-incubator/tidb-dashboard/pkg/model"

	"github.com/jinzhu/gorm"
)

func UpdateUserInfo(db *gorm.DB, userID string, name string, mail string, phone string, description string) (bool, error) {
	t := time.Now()
	result := db.Table(UserTable).
		Where("user_id = ?", userID).
		Updates(model.User{
			LoginTime:   &t,
			Name:        name,
			Mail:        mail,
			Phone:       phone,
			Description: description,
		})
	if result.Error != nil {
		return false, ErrExecute.Wrap(result.Error, "update login time error")
	}
	return result.RowsAffected != 0, nil
}

func CreateUser(db *gorm.DB, user *model.User) error {
	//创建用户，初始化角色
	if err :=
		db.Table(UserTable).
			Create(&user).
			Error; err != nil {
		return ErrExecute.Wrap(err, "insert user error")
	}
	var role model.Role
	err := db.Table(RoleTable).Find(&role, "role =  ?", "user").Error
	if err != nil {
		return ErrExecute.Wrap(err, "get role error")
	}
	t := time.Now()
	userRole := &model.UserRole{
		RoleID:     role.ID,
		UserID:     user.UserID,
		CreateTime: &t,
	}
	if err :=
		db.Table(UserRoleTable).
			Create(&userRole).
			Error; err != nil {
		return ErrExecute.Wrap(err, "insert user role error")
	}
	return nil
}

func DeleteUser(db *gorm.DB, userID string) error {
	if err :=
		db.Table(UserTable).
			Where("user_id = ?", userID).
			Delete(model.User{}).Error; err != nil {
		return ErrExecute.Wrap(err, "delete user error")
	}
	return nil
}

func GetUser(db *gorm.DB, userID string) (*model.User, error) {
	var users []model.User
	err := db.Table(UserTable).Where("user_id = ? ", userID).Scan(&users).Error
	if err != nil {
		return nil, ErrExecute.Wrap(err, "get user error")
	}
	if len(users) == 0 {
		return nil, nil
	}
	return &users[0], nil
}

func GetUsers(db *gorm.DB) ([]model.User, error) {
	var users []model.User
	err := db.Raw("SELECT * FROM tidb_dashboard.user order by create_time desc ").
		Scan(&users).Error

	if err != nil {
		return nil, err
	}
	return users, nil
}
